package com.iemes.controller.system;


import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.RoleFormMap;
import com.iemes.entity.UserFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.UserMapper;
import com.iemes.service.system.UserService;
import com.iemes.util.Common;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ResponseHelp;
import com.iemes.util.ShiroSecurityHelper;

/**
 * 
 * @author huahao
 * 
 */
@Controller
@RequestMapping("/system/user/")
public class UserController extends BaseController {
	
	@Inject
	private UserMapper userMapper;
	
	@Inject
	private UserService userService;
	
	//用户管理界面
	private String userManagerUrl = Common.BACKGROUND_PATH + "/system/user/user_manager";
	
	//修改密码界面
	private String updateUserPasswordUrl = Common.BACKGROUND_PATH + "/system/user/user_update_password";
	
	private Logger log = Logger.getLogger(this.getClass());
	
	@RequestMapping("list")
	public String listUI(Model model,HttpServletRequest request) throws Exception {
		RoleFormMap roleFormMap = new RoleFormMap();
		roleFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
		List<RoleFormMap> list = userMapper.findByNames(roleFormMap);
		model.addAttribute("noBindRoleList", list);
		model.addAttribute("bindRoleList", null);
		handlePageRes(model,request);
		return userManagerUrl;
	}
	
	/**
	 * 保存用户
	 * @param roleSelectGroups
	 * @return
	 */
	@ResponseBody
	@RequestMapping("saveUser")
	@SystemLog(module="系统管理",methods="用户管理-保存用户")//凡需要处理业务逻辑的.都需要记录操作日志
	public String save(){
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		userFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
		userFormMap.put("create_time", DateUtils.getStringDateTime());
		userFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
		String msg = "用户信息保存成功";
		
		try {
			String message = userService.saveUser(userFormMap);
			if (!StringUtils.isEmpty(message)) {
				msg = message;
			}
		}catch(BusinessException e) {
			log.error(e.getMessage());
			return ResponseHelp.responseErrorText(e.getMessage());
		}
		return ResponseHelp.responseText(msg);
	}
	
	/**
	 * 重置密码
	 * @param roleSelectGroups
	 * @return
	 */
	@ResponseBody
	@RequestMapping("resetPass")
	@SystemLog(module="系统管理",methods="用户管理-重置密码")
	public String resetPass(){
		UserFormMap userFormMap = getFormMap(UserFormMap.class);
		String id = userFormMap.getStr("id");
		if (StringUtils.isEmpty(id)) {
			String msg = "请先检索后再执行重置密码操作！";
			log.error(msg);
			return ResponseHelp.responseErrorText(msg);
		}
		try {
			userService.resetPass(userFormMap);
		}catch(BusinessException e) {
			log.error(e.getMessage());
			return ResponseHelp.responseErrorText(e.getMessage());
		}
		return ResponseHelp.responseText();
	}
	
	/**
	 * 检索用户
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("queryUser")
	public String queryUser(Model model,HttpServletRequest request) {
		String account_name = request.getParameter("account_name");
		UserFormMap userFormMap = new UserFormMap(); 
		userFormMap.put("account_name", account_name);
		
		List<UserFormMap> listUserFormMap = userMapper.findByNames(userFormMap);
		if (!ListUtils.isNotNull(listUserFormMap)) {
			log.error("未检索到用户名为："+account_name.toUpperCase()+"的用户信息");
			RoleFormMap roleFormMap = new RoleFormMap();
			List<RoleFormMap> list = userMapper.findByNames(roleFormMap);
			model.addAttribute("noBindRoleList", list);
			model.addAttribute("bindRoleList", null);
			model.addAttribute("errorMessage", "未检索到用户名为："+account_name.toUpperCase()+"的用户信息");
			handlePageRes(model,request);
			return userManagerUrl;
		}
		userFormMap = listUserFormMap.get(0);
		model.addAttribute("user", userFormMap);
		
		RoleFormMap noBindRole = new RoleFormMap();
		noBindRole.put("where", " WHERE id NOT IN (SELECT role_id FROM `mds_user_role` WHERE user_id = '"+userFormMap.getStr("id")+"') and site_id ='"+ ShiroSecurityHelper.getSiteId() +"'");
		List<RoleFormMap> noBindRoleList = userMapper.findByWhere(noBindRole);
		
		RoleFormMap bindRole = new RoleFormMap();
		bindRole.put("where", " WHERE id IN (SELECT role_id FROM `mds_user_role` WHERE user_id = '"+userFormMap.getStr("id")+"')");
		List<RoleFormMap> bindRoleList = userMapper.findByWhere(bindRole);
		
		model.addAttribute("noBindRoleList", noBindRoleList);
		model.addAttribute("bindRoleList", bindRoleList);
		model.addAttribute("successMessage", "检索成功");
		handlePageRes(model,request);
		return userManagerUrl;
	}
	
	/**
	 * 删除用户
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("delUser")
	public String delUser(Model model,HttpServletRequest request) {
		String id = request.getParameter("user_id");
		try {
			if (StringUtils.isEmpty(id)) {
				throw new BusinessException("操作失败，参数不能为空！");
			}
			userService.delUser(id);	
		}catch(BusinessException e) {
			log.error(e.getMessage());
			RoleFormMap roleFormMap = new RoleFormMap();
			List<RoleFormMap> list = userMapper.findByNames(roleFormMap);
			model.addAttribute("noBindRoleList", list);
			model.addAttribute("bindRoleList", null);
			model.addAttribute("errorMessage", e.getMessage());
			handlePageRes(model,request);
			return userManagerUrl;
		}
		RoleFormMap roleFormMap = new RoleFormMap();
		List<RoleFormMap> list = userMapper.findByNames(roleFormMap);
		model.addAttribute("noBindRoleList", list);
		model.addAttribute("bindRoleList", null);
		model.addAttribute("successMessage", "删除用户信息成功");
		handlePageRes(model,request);
		return userManagerUrl;
	}
	
	@RequestMapping("updatePassView")
	public String updatePassView(Model model) throws Exception {
		return updateUserPasswordUrl;
	}
	
	/**
	 * 修改密码
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("updatePass")
	public String updatePass(Model model) throws Exception {
		try {
			UserFormMap userFormMap = getFormMap(UserFormMap.class);
			String oldPassword = userFormMap.getStr("oldPassword");
			String newPassword = userFormMap.getStr("newPassword");
			String newPassword2 = userFormMap.getStr("newPassword2");
			if (!newPassword.equals(newPassword2)) {
				throw new BusinessException("新密码与确认密码不一致");
			}
			if (StringUtils.isEmpty(oldPassword)) {
				throw new BusinessException("旧密码不能为空！！！");
			}
			if (StringUtils.isEmpty(newPassword)) {
				throw new BusinessException("新密码不能为空！！！");
			}
			if (StringUtils.isEmpty(newPassword2)) {
				throw new BusinessException("确认密码不能为空！！！");
			}
			userService.updatePass(userFormMap);
		}catch(BusinessException e) {
			String msg = e.getMessage();
			log.error(msg);
			return ResponseHelp.responseErrorText(msg);
		}
		return ResponseHelp.responseText();
	}
}